<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;
error_reporting(0);
use app\admin\service\NodeService;
use library\Controller;
use library\tools\Data;
use think\Console;
use think\Db;
use think\facade\Config;
use think\page;
use think\exception\HttpResponseException;
use app\admin\model\Document;
use app\admin\model\Flow;



/**
 * 系统公共操作
 * Class Index
 * @package app\admin\controller
 */
class Index extends Controller
{

    /**
     * 显示后台首页
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->title = '网上自动办公系统';
        NodeService::applyUserAuth(true);
        $this->menus = NodeService::getMenuNodeTree();

        if (empty($this->menus) && !NodeService::islogin()) {
            $this->redirect('@admin/login');
        } else {
			
			$allusers = session('admin_user')['nickname'];
	        $daiban_num = Db::table('Document')->alias('d')
				->join('Flow f','d.id=f.docid')
	            ->where( "f.username ='".$allusers."' AND f.status=1 AND d.status=1 AND f.info ='' AND f.flag<5 ")
	            ->count();
			
	        $xiujia_num = Db::table('Users_Jiaqi')->alias('d')
				->join('users_jiaqi_flow f','d.id=f.docid')
	            ->where( "f.username ='".$allusers."' AND f.status=1 AND d.status=0 AND f.info ='' ")
	            ->count();
	        


			foreach($this->menus as &$v){
				if($v['id']==62){
					$v['badge'] =$daiban_num;
				}elseif($v['id']==77){
					$v['badge'] =$xiujia_num;
				}
			}

            $this->fetch();
        }
    }

    /**
     * 后台环境信息
     */
    public function main()
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！' ,'admin/login');
        }

        $allusers = session('admin_user')['nickname'];
        $rs = Db::table('Docoutflow')
            ->where( "  username ='".$allusers."' AND status=1 AND info ='' ")
            ->select();

        
        $doc1 = Db::table('Docoutflow')->alias('a')
				->field(' a.username,    b.id, b.title,a.doctypes , b.docdate')
        		->join('Docout b','a.docid=b.id')
				->where('a.username','eq',$allusers)
				->where("b.status=1 AND a.status=1 AND a.info= '' ")
				//->paginate(3,true);
				->select();

        foreach ($doc1 as &$v) {
        	if($v['doctypes'] =='docout'){
        		$v['spm'] ='m-66-67-68';
        	}elseif ($v['doctypes'] =='docnone') {
        		$v['spm'] ='m-66-70-71';
            }elseif ($v['doctypes'] =='stamp') {
                $v['spm'] ='m-77-81-82';
        	}elseif ($v['doctypes'] =='news') {
        		$v['spm'] ='m-73-74-75';
            }elseif ($v['doctypes'] =='docin') {
                $v['spm'] ='m-85-86-87';
        	}

        }


        $doc3 = Db::table('Users_Jiaqi_Flow')->alias('a')
				->field(' `b`.`id`,`a`.`docid`,`a`.`username`,`a`.doctypes,`a`.`addtime` ')
        		->join('users_jiaqi b','a.docid=b.id')
				->where('a.username','eq',$allusers)
				->where("b.status=0 AND a.status=1 AND a.info= '' ")
				//->paginate(3,true);
				->select();
        foreach ($doc3 as &$v) {
			$v['title'] =$v['username'].'的请假条';
			$v['spm'] ='m-77-88-92';
        }
        
		$today =date('Y-m-d' ,time());
        $news =Db::table('Notice')->field('id , create_at , docdept, title')->where(" is_deleted=0 AND status=1 AND wenhao=3 AND 
		TO_DAYS(NOW()) - TO_DAYS(`docenddate`) <= 7 ")->order('id DESC')->select();

        $this->think_ver = \think\App::VERSION;
        $this->mysql_ver = Db::query('select version() as ver')[0]['ver'];
        $this->assign('news' , $news);
        $this->assign('doc1' , $doc1);
        $this->assign('doc3' , $doc3);
        $this->fetch();
    }


	public function getDocList()
	{
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！' ,'admin/login');
        }

        $allusers = session('admin_user')['nickname'];
		
		list($data1, $string) = [$this->request->post(), []];
		
		//$page =$this->request->param('page');
		
		//print_r($data1['page']);		
		
		$page = empty($data1['page']) ? 1 : intval($data1['page']);//获取当前页数
		$pageSize = empty($data1['pageSize']) ? 10 : intval($data1['pageSize']);//获取当前页数
		
		
		$doc2 = array();
        $doc2= Db::table('Flow')->alias('a')
			->field(' a.username,    b.id, b.title,a.doctypes , b.docdate')
			//->group('a.username')
        	->join('Document b','a.docid=b.id')
			->where('a.username','eq',$allusers)
			->where("b.status=1 AND a.status=1 AND a.info= '' ")->order('b.id DESC')->page($page, $pageSize)->select();  //->paginate(2,true);
			

		foreach($doc2 as &$v){
			$v['docdate'] =date('m-d' , strtotime($v['docdate']));
		}

		
        $count= Db::table('Flow')->alias('a')
			->field(' a.username,    b.id, b.title,a.doctypes , b.docdate')
			//->group('a.username')
        	->join('Document b','a.docid=b.id')
			->where('a.username','eq',$allusers)
			->where("b.status=1 AND a.status=1 AND a.info= '' ")->count();
			
		$sum = ceil($count/$pageSize);//要分多少页	
		
		$data =[];
		$data['errcode'] =0;
		$data['body']['rows'] =$doc2;
		$data['body']['total'] =$count;
		$data['body']['pageCount'] =$sum;
		
		return ($data);

	}



    /**
     * 修改密码
     * @param integer $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass($id)
    {
        $this->applyCsrfToken();
        if (intval($id) !== intval(session('admin_user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        if ($this->request->isGet()) {
            $this->verify = true;
            $this->_form('SystemUser', 'admin@user/pass', 'id', [], ['id' => $id]);
        } else {
            $data = $this->_input([
                'password'    => $this->request->post('password'),
                'repassword'  => $this->request->post('repassword'),
                'oldpassword' => $this->request->post('oldpassword'),
            ], [
                'oldpassword' => 'require',
                'password'    => 'require|min:4',
                'repassword'  => 'require|confirm:password',
            ], [
                'oldpassword.require' => '旧密码不能为空！',
                'password.require'    => '登录密码不能为空！',
                'password.min'        => '登录密码长度不能少于4位有效字符！',
                'repassword.require'  => '重复密码不能为空！',
                'repassword.confirm'  => '重复密码与登录密码不匹配，请重新输入！',
            ]);
            $user = Db::name('SystemUser')->where(['id' => $id])->find();
            if (md5($data['oldpassword']) !== $user['password']) {
                $this->error('旧密码验证失败，请重新输入！');
            }
            $result = NodeService::checkpwd($data['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save('SystemUser', ['id' => $user['id'], 'password' => md5($data['password'])])) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 修改用户资料
     * @param integer $id 会员ID
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function info($id = 0)
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        $this->applyCsrfToken();
        if (intval($id) === intval(session('admin_user.id'))) {
            $this->_form('SystemUser', 'admin@user/form', 'id', [], ['id' => $id]);
        } else {
            $this->error('只能修改登录用户的资料！');
        }
    }

    /**
     * 清理运行缓存
     * @auth true
     */
    public function clearRuntime()
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        try {
            Console::call('clear');
            Console::call('xclean:session');
            $this->success('清理运行缓存成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("清理运行缓存失败，{$e->getMessage()}");
        }
    }

    /**
     * 压缩发布系统
     * @auth true
     */
    public function buildOptimize()
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        try {
            Console::call('optimize:route');
            Console::call('optimize:schema');
            Console::call('optimize:autoload');
            Console::call('optimize:config');
            $this->success('压缩发布成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("压缩发布失败，{$e->getMessage()}");
        }
    }

    /**
     * 签名设置
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function signature($id)
    {
        if (!NodeService::islogin()) {
            $this->error('需要登录才能操作哦！');
        }
        $this->applyCsrfToken();
        if (intval($id) === intval(session('admin_user.id'))) {

             //print_r(Config::get('app.attchment')['path']);
             $rss =Db::name('Signature')->where('nickname',session('admin_user.nickname'))->select();
             $this->assign('rss' , $rss);
            $this->_form('SystemUser', 'admin@user/signature', 'id', [], ['id' => $id]);
        } else {
            $this->error('只能修改登录用户的资料！');
        } 
    }  

    /**
     * 签名保存
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function savesig()
    {
        if ($this->request->isPost()) {
            list($data1, $string) = [$this->request->post(), []];
            $id =intval($this->request->param('id'));

            $rs =Db::name('SystemUser')->where('id',$id)->find();
            $user = session('admin_user')['username'];
            if ($rs['username'] !=$user) {
                $res['code'] =1;
                $res['info'] ='你只能修改自己的签名';
                return $res;
            }

            //更新
           //$data1['signatureurl'] =$data1['signatureurl'];

           $data1['signatureurl'] = base64_image_content($data1['signatureurl'] , Config::get('app.signature')['path'] );



            Db::name('SystemUser')
                ->where('id', $id)
                ->strict(false)
                ->data($data1)
                ->update();   

            $nickname = session('admin_user')['nickname'];
            $data2 =[];
            $data2['sigtitle'] =$data1['sigtitle'];
            $data2['nickname'] =$nickname;
            $data2['addtime'] =time();
            $data2['sigurl'] = $data1['signatureurl'];

            $ids =Db::name('Signature')->strict(false)->insertGetId($data2);
            if($ids >0){
                $res['code'] =0;
                $res['info'] ='保存成功';
                return $res; 
            }
        }
    }

    /**
     * 签名删除
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delsig()
    {
        list($data1, $string) = [$this->request->post(), []];

        $rs =Db::name('Signature')->where('id',$data1['id'])->find();
        $user = session('admin_user')['nickname'];
        if ($rs['nickname'] !=$user) {
            $res['code'] =1;
            $res['info'] ='你只能删除自己的签名';
            return $res;
        }

        Db::table('Signature')->where(" id='".$data1['id']."' ")->delete();
        $res['code'] =0;
        $res['info'] ='删除成功';
        return $res; 

    }

	/*普通上传*/
    public function upload()
    {
        if($this->request->file('file')){
            $file       = $this->uploadfile('file','' ,[] , session('admin_user')['id']);
            if ($file) {
                echo json_encode($file);
            } else {
                echo json_encode($file);
            }
        }
    }

	/*普通上传详细过程*/
    public function uploadfile($name, $path = '', $validate = [], $user_id = 0)
    {
        $config = config('signature');
        $file   = request()->file($name);
        if ($file) {
            $file_path = $config['path'] . $path;
            $file_url  = $config['url'] . $path;
            $validate  = array_merge($config['validate'], $validate);
            $info      = $file->validate($validate)->move($file_path);
            if ($info) {
                $file_info = [
                    'code'          => 0 ,
                    'user_id'       => $user_id,
                    'original_name' => $info->getInfo('name'),
                    'save_name'     => $info->getFilename(),
                    'save_path'     => str_replace("\\", "/",$file_path . $info->getSaveName()),
                    'extension'     => $info->getExtension(),
                    'mime'          => $info->getInfo('type'),
                    'size'          => $info->getSize(),
                    'md5'           => $info->hash('md5'),
                    'sha1'          => $info->hash(),
                    'url'           => str_replace("\\", "/",$file_url . $info->getSaveName()),
					'location'      => str_replace("\\", "/",$file_url . $info->getSaveName())
                ];
                return $file_info;
            } else {
                return $file->getError();
            }
        } else {
            return '无法获取文件';
        }
        return false;
    }

	/*编辑器内base64上传*/
    public function savepic()
    {
        if ($this->request->isPost()) {
            list($data1, $string) = [$this->request->post(), []];

            $data1['picdata'] = base64_image_content($data1['picdata'] , rtrim(Config::get('app.attchment')['path'],'/') );
  
            $res['code'] =0;
            $res['info'] ='保存成功';
            $res['url'] =$data1['picdata'];
            $res['location'] =$data1['picdata'];
            return $res;

        }
    }

	/*编辑器内二进制流上传*/
    public function uploadBin()
    {
        ob_start(); //打开缓冲区
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件

        list($data1, $string) = [$this->request->get(), []];

        $streamData = file_get_contents('php://input' ) ? file_get_contents ('php://input') : gzuncompress ($GLOBALS ['HTTP_RAW_POST_DATA']);

        if(empty($streamData)){  
           //$streamData = file_get_contents('php://input');  
           echo ('201|||没有接收到数据流.' );
           die();
        }

        if( !in_array( $data1['ext']  , explode(',' , Config::get('app.attchment')['validate']['ext'])) ){
            echo ('202|||文件格式错误!' );
            die();
        }
		
        if ($this->request->isPost()) {

            $new_file = Config::get('app.attchment')['path'].date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdirs($new_file, 0700);
            }

            $file = $new_file . time() .'.'.$data1['ext'];
            file_put_contents( $file , $streamData , true);
            echo '200|||'.'/'.$file;
            die();

        }
    }










}
